/*
 *    Copyright (c) 2023 李伟国
 *    moyu is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 */

package cn.moyu.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.SpringBootConfiguration;

import java.util.Date;

/**
 * Mybatis的自动填充
 */

@SpringBootConfiguration
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean createTime = metaObject.hasGetter(MetaConstant.createTime);
        if(createTime){
            this.setFieldValByName(MetaConstant.createTime, new Date(), metaObject);
        }
        boolean isUsed = metaObject.hasGetter(MetaConstant.isUsed);
        if(isUsed){
            this.setFieldValByName(MetaConstant.isUsed, 1, metaObject);
        }
        boolean isDeleted = metaObject.hasGetter(MetaConstant.isDeleted);
        if(isDeleted){
            this.setFieldValByName(MetaConstant.isDeleted, 0, metaObject);
        }
        boolean updateTime = metaObject.hasGetter(MetaConstant.updateTime);
        if(updateTime){
            this.setFieldValByName(MetaConstant.updateTime, new Date(), metaObject);
        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        boolean updateTime = metaObject.hasGetter(MetaConstant.updateTime);
        if(updateTime){
            this.setFieldValByName(MetaConstant.updateTime, new Date(), metaObject);
        }
    }
}
interface MetaConstant{
    String createTime = "createTime";
    String updateTime = "updateTime";

    String isUsed = "isUsed";
    String isDeleted = "isDeleted";
}
